import {
  Authenticated,
  GetLoginDetails,
  PublicRoute,
  Auth,
} from '@app/middleware/auth.guard';
import { ApiTags } from '@nestjs/swagger';
import { Body, Controller, Post, Res, HttpCode, HttpStatus, Req } from '@nestjs/common';
import { AuthService, LoginDetails } from '@app/services/auth.service';
import { LoginCredentialDto, LoginResponseDto, AuthDto } from '@app/dtos/auth.dto';
import { Request, Response } from 'express';
import { respondWithoutCookie } from '@app/utils/response';

import { AuthType, LOGIN_URL } from '@app/constant';

@ApiTags('Authentication')
@Controller('auth')
@Authenticated()
export class AuthController {
  constructor(private service: AuthService) {}

  @PublicRoute()
  @Post('login')
  async login(
    @Body() loginCredential: LoginCredentialDto,
    @Res({ passthrough: true }) res: Response,
    @GetLoginDetails() loginDetails: LoginDetails,
  ): Promise<LoginResponseDto> {
    const { response } = await this.service.login(
      loginCredential,
      loginDetails,
    );
    // res.header('Set-Cookie', cookie);
    return response;
  }

  @Post('logout')
  @HttpCode(HttpStatus.OK)
  @Authenticated()
  async logout(
    @Req() request: Request,
    @Res({ passthrough: true }) res: Response,
    @Auth() auth: AuthDto,
  ) {
    // const authType = (request.cookies || {})[AUTH_TYPE];
    const body = await this.service.logout(auth, AuthType.PASSWORD);

    return respondWithoutCookie(res, body, []);
  }
}
